<template>
  <el-container>
    <el-header>
      <h1>新闻管理</h1>
    </el-header>
    <div style="display: flex ;margin-left: 500px">
<!--      <el-input v-model="input" style="width: 240px" placeholder="请输入" />-->
<!--      <el-button :disabled="input.length===0" @click='setInfo'  type="primary">搜索</el-button>-->
      <el-button @click="addBrand" style="width: 100px;margin-left: 350px" type="info">添加新闻</el-button></div>
    <el-main>
      <el-table :data="news" style="width: 100%" >
        <el-table-column prop="head" label="新闻标题" width="300"></el-table-column>
        <el-table-column prop="images" label="新闻图片" width="200">
          <template #default="{ row }">
            <img :src="row.images" alt="新闻图片" style="width: 200px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="newsTime" label="最后一次更新时间" width="200px"></el-table-column>
        <el-table-column label="操作" width="500" >
          <template #default="{ row }">
            <el-button  type="primary" size="small" @click="editBrand(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteBrand(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination v-model:current-page="pageNumber" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
                     layout="jumper, total, sizes, prev, pager, next" background :total="total"
                     @size-change="onSizeChange"
                     @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
    </el-main>
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" title="新闻操作" direction="rtl" size="50%">
      <!-- 添加文章表单 -->
      <el-form :model="newsModel" label-width="100px">
        <el-form-item label="新闻标题"><el-input v-model="newsModel.head"  style="width: 400px" type="textarea" placeholder="请输入新闻标题" /></el-form-item>
        <el-form-item label="新闻图片" >
          <el-upload class="avatar-uploader" on-exceed="exceeds" :auto-upload="true" :show-file-list="false"  element-loading-text="正在上传" action="http://localhost:8080/upload"  name="file" :headers="{'Authorization':tokenStore.token.data}"
                     :on-success='uploadSuccess'>
            <img width="50px" height="50px" v-if="newsModel.images" :src="newsModel.images" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="新闻描述">
          <div class="editor">
            <el-input
                v-model="newsModel.content"
                style="width: 300px"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入新闻内容"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tokeBrand">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-container>
</template>

<script setup>

import {ref} from "vue";
import {useTokenSotre} from "@/stores/token";
import {ElMessage, ElMessageBox} from "element-plus";
const tokenStore = useTokenSotre()
console.log(tokenStore.token)
const news = ref()
const editBrand = (row)=>{
  drawer.value=1
  newsModel.value.id = news.value[row.id-1].id
  newsModel.value.head=news.value[row.id-1].head
  newsModel.value.images=news.value[row.id-1].images
  newsModel.value.content=news.value[row.id-1].content
  visibleDrawer.value=true
  fix.value=0
}
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  setInfo()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNumber.value = num
  setInfo()
}

const input=ref('')
//添加新闻
const addBrand = ()=>{
  drawer.value=0
  visibleDrawer.value=true
  clearInfo()
}
const clearInfo=()=>{
  newsModel.value.head=''
  newsModel.value.images=''
  newsModel.value.content= ''
}
const drawer = ref(0)
//删除分类
const deleteBrand=(row)=>{
  ElMessageBox.confirm(
      '请问您确定要删除吗',
      '提醒',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await deleteNewsService(row.ids)
        clearInfo()
        setInfo()
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
//控制抽屉是否显示
const visibleDrawer = ref(false)
const exceeds=()=>{
  ElMessage.error("图片过大")
}

const newsModel = ref({
  id:'',
  head:'s',
  images: '',
  content:'',
  newsTime: '',
})


import {deleteNewsService, newsInsertService, upNewsInfoService} from '@/api/news'
const fix = ref(1)
const tokeBrand = async ()=>{
  // newsModel.value.newsTime = new Date().getTime()
  if (fix.value===1){
    newsInsertService(newsModel.value)
    ElMessage.success("添加成功")
  }else {
    updateInfo()
  }
  visibleDrawer.value=false
  clearInfo()
  setInfo()
}

//上传成功的回调函数
const uploadSuccess=(result)=>{
  newsModel.value.images = result.data
}
import {newsInfoService} from '@/api/news'
const pageNumber = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(3)//每页条数
const setInfo=async ()=>{
  let params = {
    pageNumber: pageNumber.value,
    pageSize: pageSize.value,
  }
  let result =await newsInfoService(params)
  console.log(result)
  news.value = result.data.records;
  total.value=result.data.total
}
setInfo()
const updateInfo=async ()=>{
  await upNewsInfoService(newsModel.value)
  ElMessage.success("修改成功")
  setInfo()
}


</script>